package com.zy.server.service.impl;

import com.zy.config.RedisKeyConfig;
import com.zy.config.SystemConfig;
import com.zy.server.dao.UserdetailMapper;
import com.zy.server.entity.Osslog;
import com.zy.server.dao.OsslogMapper;
import com.zy.server.service.OsslogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.server.util.AliOssUtil;
import com.zy.server.util.BaidCensorUtil;
import com.zy.third.JedisUtil;
import com.zy.util.DateUtil;
import com.zy.util.StrUtil;
import com.zy.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张鑫
 * @since 2020-11-27
 */
@Service
public class OsslogServiceImpl extends ServiceImpl<OsslogMapper, Osslog> implements OsslogService {

    @Autowired
    private OsslogMapper osslogMapper;
    @Autowired
    private UserdetailMapper userdetailMapper;

    // 存储空间名称。已经建好
    private final String bname = "zhangxinhope";

    @Override
    @Transactional  // 开启事务
    public R upload(MultipartFile file, String token) {
        if (!file.isEmpty()) {
            try {
                byte[] data = file.getBytes();

                if (BaidCensorUtil.censorImg(data)) {
                    // 文件名
                    String filename = file.getOriginalFilename();
                    filename = renameFn(filename);

                    // 存在哪，上传到oss并且获取访问路径
                    String url = AliOssUtil.upload(bname, filename, SystemConfig.PIC_URLTIME, data);
                    if (StrUtil.checkNoEmpty(url)) {

                        // 当前应该获取用户信息
                        //int uid = Integer.parseInt(JedisUtil.getInstance().getStr(RedisKeyConfig.AUTH_TOKEN+token));
                        int uid = 2;
                        // 记录到数据库,同时存入用户uid到头像日志表
                        Osslog osslog = new Osslog(filename, bname, url, 1, DateUtil.addTime(SystemConfig.PIC_URLTIME, 3),uid);
                        osslogMapper.insertId(osslog);

                        // 当头像上传后，把oid存入用户详情表
                        userdetailMapper.updateOid(osslog.getId(), uid);

                        return R.ok(url);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("亲，该头像虽然美，但是不符合要求哦~");
    }

    // 文件重命名和长度截取
    private String renameFn(String name) {
        // 防止上传的文件名太长不能超过30
        if (name.length() > 30) {
            name = name.substring(name.length() - 30);
        }

        return System.currentTimeMillis() + "-" + name;
    }
}
